package com.sky.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.jms.Session;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sky.domain.User;
import com.sky.exception.UserException;
import com.sky.service.UserService;

public class LoginFilter  implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@SuppressWarnings("null")
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request2= (HttpServletRequest)request;
		HttpServletResponse response2= (HttpServletResponse)response;
		
		/**
		 * 1.判断登录状态：
		 * 2.  如果登录了：
		 *     如果没登录，直接方向登录
		 */
		
		//从cookie(存储数据到客户端)或者session(存储数据到服务器)取登录信息
		//session的作用是判断登录状态，cookie作用是存储数据
		HttpSession session = request2.getSession();
		String name = (String) session.getAttribute("name");
         if ("".equals(name)||null==name) {
			//表示没有登录过，直接可以放行
        	 System.out.println("==没有登录过===");
		}else{
			//表示登录过了，执行自动登录：
			System.out.println("==是登录过===");
			Cookie[] cookie =request2.getCookies();
			for (int i = 0; i < cookie.length; i++) {
				Cookie c= cookie[i];
				String key = c.getName();
				if("user".equals(key)){
					//取出用户名和密码的字符串
					String value = c.getValue();
					String username =value.split("-")[0];
					String pwd =value.split("-")[1];
					System.out.println("==自动登录===");
					//做登录业务
					UserService service= new UserService();
					User user = new User();
					user.setUsername(username);
					user.setPassword(pwd);
					try {
						user = service.LoginUser(user);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (UserException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					//判断登录成功结果
					if (user!=null) {
						//自动登录成功直接跳转home.jsp
						request2.getSession().setAttribute("user", user);
						response2.sendRedirect("home/home.jsp");
					}
				}
				
			}
			
		}
         chain.doFilter(request2, response2);
		
		
		
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
